import axios from 'axios';
import Config from '~/config';

import {Loading, Message, Notification, MessageBox} from 'element-ui';
import {FormatterTime, PrefixInteger, DownFile} from '../Tools';
let {
  Local,
  Java,
  DelayLoadingCloseTime,
} = Config;

let loadinginstace = null;
let messageinstace = true;
let ycID = 0;
function errorCenter (temp1) {
  let date = new Date();
  console.error(`
异常编号： ${FormatterTime(date, 21) + PrefixInteger(ycID++, 5)} ------------------------  ${date.toLocaleString()}  ----

----> 报错后台：${Java.originUrl}
----> 请求地址：${temp1.config.url.replace(temp1.config.baseURL, '')}
----> 请求方法：${temp1.config.method.toUpperCase()}
----> 请求参数：
${temp1.config.data}
----> 请求结果：
${temp1.request.response}

---------------------------------------------------------------------------
`);
}

let hasHttp = false;
let delayTime = DelayLoadingCloseTime;
function loadingClose () {
  hasHttp = false;
  setTimeout(() => {
    if (!hasHttp) {
      if (loadinginstace && loadinginstace !== null) loadinginstace.close();
    }
  }, delayTime * 1000);
}

function requestSuccess (config) {
  hasHttp = true;
  /**
   * target       Loading 需要覆盖的 DOM 节点。
   * body         同 v-loading 指令中的 body 修饰符
   * fullscreen   同 v-loading 指令中的 fullscreen 修饰符
   * lock         同 v-loading 指令中的 lock 修饰符
   * text         显示在加载图标下方的加载文案
   * customClass  Loading 的自定义类名
   */
  let {data, headers} = config;
  let LOADING = {
    text: '拼命加载中...',
    fullscreen: true,
  };
  if (data) {
    if (!headers.sLoading) {
      let loading = data.loading;
      if (!loading) {
        loadinginstace = Loading.service(LOADING);
      } else {
        delete data.loading;
        loadinginstace = Loading.service(loading);
      }
    } else {
      delete headers.sLoading;
    }
    for (let index in data) {
      if (data.hasOwnProperty(index)) {
        if (!data[index] && data[index] !== 0) delete data[index];
        if (index === 'data') {
          let step = data[index];
          for (let i in step) {
            if (step.hasOwnProperty(i)) {
              if (!step[i] && step[i] !== 0) delete step[i];
            }
          }
        }
      }
    }
  } else {
    if (!headers.sLoading) {
      loadinginstace = Loading.service(LOADING);
    } else {
      delete headers.sLoading;
    }
  }
  return config;
}
function requestError (err) {
  if (messageinstace) {
    messageinstace = false;
    Message.error({
      message: '万分抱歉，前端数据 收集异常...',
      type: 'error',
      duration: 0,
      showClose: true,
      onClose: function () {
        messageinstace = true;
      },
    });
  }
  return Promise.reject(err);
}
function responseSuccess (res) {
  loadingClose();
  if (res.headers['content-disposition']) {
    let fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]);
    Message({
      type: 'success',
      message: '导出' + fileName,
    });
    // let contentType = res.headers['content-type'];
    let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});
    DownFile(blob, fileName);
  }
  let data = res.data;
  if (!data) return Promise.reject(res);
  let {
    messageType,
    type,
    title,
    message,
  } = data;
  if (typeof messageType !== 'undefined') {
    switch (messageType) {
    case 1:
      Notification({
        type,
        title,
        message,
        offset: 100,
      });
      break;
    case 2:
      Message({
        type,
        showClose: true,
        message: message || title,
      });
      break;
    case 3:
      MessageBox.alert({
        type,
        title,
        message,
      });
      break;
    default:
      break;
    }
    let Type = data.type;
    delete data.messageType;
    delete data.title;
    delete data.message;
    delete data.type;
    if (Type !== 'success') {
      let lastPath = res.request.responseURL.split('/');
      lastPath = lastPath[lastPath.length - 1];
      if (lastPath !== 'login' && lastPath !== 'logout' && typeof data.url !== 'undefined') {
        window.location.replace(`${Local.url}/login`);
        // postL('/logout');
      }
      errorCenter(res);
      return Promise.reject(res);
    }
  }
  return data;
}
function responseError (err) {
  if (messageinstace) {
    messageinstace = false;
    Message.error({
      message: 'T_T 服务器未响应，加载失败...',
      type: 'error',
      duration: 0,
      showClose: true,
      onClose: function () {
        messageinstace = true;
      },
    });
    errorCenter(err);
  }
  if (loadinginstace && loadinginstace !== null) loadinginstace.close();
  return Promise.reject(err);
}

/**
 * message      消息文字
 * type         主题
 * iconClass    自定义图标的类名，会覆盖
 * customClass  自定义类名
 * duration     显示时间, 毫秒。设为 0 则不会自动关闭
 * showClose    是否显示关闭按钮
 * onClose      关闭时的回调函数, 参数为被关闭的 message 实例
 */

let axiosJava = axios.create({
  baseURL: Local.interface,
});
axiosJava.defaults.withCredentials = true;
axiosJava.interceptors.request.use(requestSuccess, requestError);
axiosJava.interceptors.response.use(responseSuccess, responseError);

let axiosLocal = axios.create({
  baseURL: Local.api,
});

const p = axiosJava.request;
const get = axiosJava.get;
const del = axiosJava.delete;
const head = axiosJava.head;
const post = axiosJava.post;
const put = axiosJava.put;
const patch = axiosJava.patch;

const pL = axiosLocal.request;
const getL = axiosLocal.get;
const delL = axiosLocal.delete;
const headL = axiosLocal.head;
const postL = axiosLocal.post;
const putL = axiosLocal.put;
const patchL = axiosLocal.patch;

export {
  p,
  get,
  del,
  head,
  post,
  put,
  patch,
  pL,
  getL,
  delL,
  headL,
  postL,
  putL,
  patchL,
  axios,
  requestSuccess,
  requestError,
  responseSuccess,
  responseError,
};
